package dongshi.daddy.composite;

import dongshi.daddy.composite.component.OrganizationComponent;
import dongshi.daddy.composite.composite.OrganizationComposite;
import dongshi.daddy.composite.leaf.AdminDepartment;
import dongshi.daddy.composite.leaf.ItDepartment;
import org.junit.Test;

public class CompositeClient {

    private OrganizationComponent constructOrganization() {
        // 构建总部
        OrganizationComposite headOffice = new OrganizationComposite("总公司");
        // 总部下的叶子节点，行政部和IT部门，都没有下级部门
        AdminDepartment headAdmin = new AdminDepartment("总公司行政部");
        ItDepartment headIt = new ItDepartment("总公司It部");
        headOffice.add(headAdmin);
        headOffice.add(headIt);

        // 构建天津分公司，是非叶子节点，有下级部门
        OrganizationComposite tianjin = new OrganizationComposite("天津分公司");
        AdminDepartment tianjinAdmin = new AdminDepartment("天津分公司行政部");
        ItDepartment tianjinIT = new ItDepartment("天津分公司It部");
        tianjin.add(tianjinAdmin);
        tianjin.add(tianjinIT);

        // 将天津分公司加入到head中
        headOffice.add(tianjin);

        return headOffice;
    }

    @Test
    public void listOrgInfo() {
        OrganizationComponent org = constructOrganization();
        System.out.println(String.format("%s共有%d名员工",
                org.getName(), org.getStaffCount()));

        OrganizationComponent subOrg = org.getChild("天津分公司行政部");
        System.out.println(String.format("%s共有%d名员工",
                subOrg.getName(), subOrg.getStaffCount()));
    }

    @Test
    public void treeInfo() {
        OrganizationComponent org = constructOrganization();
        OrganizationComposite head = (OrganizationComposite) org;

        show1(head, 0);
    }

    private void show1(OrganizationComposite head, int indent) {
        if (head == null) return;
        String indentStr = makeIndent(indent);
        System.out.println(indentStr + head.getName());
        head.getOrganizations().forEach(c-> {
            if (c instanceof OrganizationComposite) {
                show1(((OrganizationComposite) c), indent + 1);
            } else {
                System.out.println(makeIndent(indent + 1) + c.getName());
            }
        });
    }

    private String makeIndent(int indent) {
        String indentStr = "";
        for (int i = 0; i < indent; i++) {
//            indentStr += "=";
            indentStr += " ";
        }
        return indentStr;
    }

    private void show(OrganizationComposite head) {
        if (head == null) return;
        System.out.println(head.getName());
        head.getOrganizations().forEach(c-> {
            if (c instanceof OrganizationComposite) {
                show(((OrganizationComposite) c));
            } else System.out.println(c.getName());
        });
    }
}